Splitting up project with react & webpack4; html tags are unexpected tokens

杀马特。学长 韩版系。学妹 提交于 2019-12-02 11:19:14

问题


Background

I'm using react, babel, webpack4, and es6(or maybe es7)

I have some modules that are reused by multiple react projects. For this reason I've created a 'Standard' folder that contains these modules so that they are kept separate from any specific project.

Problem

In my react project I edited my webpack.config.js to contain

  resolve: {
    extensions: ['.css', '.js', '.jsx'],
    alias: {
      Standard: '/Path/To/Standard',
    }
  }

Then to import a module from it I call

import MyModule from 'Standard/MyModule.js'

When I do this, it looks like the html tags aren't recognized within the files in my Standard folder

Error Messages

For webpack-dev-server --inline

ERROR in /Path/To/Standard/MyModule.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Path/To/Standard/MyModule.js: Unexpected token (13:8)

  11 | var MyModule = (props) => {
  12 |     return (
> 13 |         <header id='Header' className={props.className}>

For webpack

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! default@1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the default@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Debugging attempts

I've tried to create a webpack.config.js and package.json inside my standard folder(in addition to my project folder), but nothing really seems to help

I tried some npm installs to install babel, because that seemed like the most obvious solution, and is used on this answer in an older webpack version, but I still get the same problems

  npm install --save react
  npm install --save babel @babel/cli @babel/core @babel/preset-env @babel/preset-react
  npm install --save babel-core babel-loader babel-cli babel-preset-env babel-preset-react webpack

Also it looks like this post which is a reply to this blog might be related, but this solution didn't work for me.


package.json

{
    "scripts": {
        "webpack": "webpack",
        "start": "http-server"
    },
    "dependencies": {
        "react": "^16.8.6"
    },
    "devDependencies": {
        "@babel/cli": "^7.5.5",
        "@babel/core": "^7.5.5",
        "@babel/plugin-proposal-object-rest-spread": "^7.5.1",
        "@babel/polyfill": "^7.4.4",
        "@babel/preset-env": "^7.5.0",
        "@babel/preset-react": "^7.0.0",
        "babel-loader": "^8.0.6",
        "webpack": "^4.28.0"
    }
}

webpack.config.js

var webpack = require('webpack');

const config = {
    mode: 'development',     // set mode option, 'development' or 'production'
    module: {
      rules: [
        {
          test: /\.m?js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
        }
      ]
    },
    resolve: {
      extensions: ['.css', '.js', '.jsx'],
    }
}

module.exports = config;

.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": [
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ]
  ]
}

回答1:


You're 1st problem here is that babel is not parsing code from you're packages (error say that it try to exec not transpiled jsx code).

Maybe the babel presets is not accessible in you're package directory. You can try copying them or set them directly in the webpack config

                    {
                        loader : 'babel-loader',
                        options: {
                            presets       : [
                                ['@babel/preset-env',
                                    {// here the presets params
                                    }],
                                '@babel/preset-react'
                            ],
                            plugins       : [
                                ['@babel/plugin-proposal-class-properties', {
                                    "loose": true
                                }]
                            ]
                        }
                    },

Possibly the exclude regexp of babel exclude the packages from where you want importing scripts :

     exclude: /(node_modules|bower_components)/,

So you can use a custom function like that :

     exclude: {test:(pathName)=>(isInternalCode(pathName))),

Or use negative lookahead in the reg exp like :

/(node_modules(?!\b(?:OneFolder|AnotherIncluded))|bower_modules)/

That's said the usual way is to compile independently you're packages ( by externalizing all theirs deps from the builds & adding them to "peerDependencies" or "dependencies" )

Also; there a plugin to make "inheritable" packages; webpack-inherit.

It allow making "inheritable" projects, & deal with node_modules & webpack to make inheritable "code layers" & even work when compiling node scripts or using monorepo structure

Using it you can simply put you're components in a shared inheritable package

it come with some nice features like glob resolving, which help including an unknown number of files.

There is samples here & doc here

Hope it help :)



来源:https://stackoverflow.com/questions/57261894/splitting-up-project-with-react-webpack4-html-tags-are-unexpected-tokens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!